import type { RedisClient } from "@linksaas-minapp/redis-proxy-api"
import { Descriptions } from "antd";
import { useEffect, useState } from "react"
import StringValue from "./components/StringValue";
import SetValue from "./components/SetValue";
import SortedSetValue from "./components/SortedSetValue";
import HashValue from "./components/HashValue";
import ListValue from "./components/ListValue";

export interface DetailProps {
    client: RedisClient;
    curKey: string;
}

function Detail(props: DetailProps) {
    const [dataType, setDataType] = useState<string | null>(null);
    const [dataIdleTime, setDataIdleTime] = useState<number | null>(null);
    const [dataTtl, setDataTtl] = useState<number | null>(null);

    const loadKeyData = async () => {
        setDataType(null);
        setDataIdleTime(null);
        setDataTtl(null);

        const t = await props.client.coreCommand().getType(props.curKey);
        setDataType(t);
        const idleTime = await props.client.coreCommand().objectIdleTime(props.curKey);
        setDataIdleTime(idleTime);
        const ttl = await props.client.coreCommand().ttl(props.curKey);
        if (ttl > 0) {
            setDataTtl(ttl);
        }
    };

    const getDataTypeStr = () => {
        if (dataType == "string") {
            return "字符串";
        } else if (dataType == "set") {
            return "集合";
        } else if (dataType == "zset") {
            return "有序集合";
        } else if (dataType == "hash") {
            return "哈希表";
        }else if(dataType == "list"){
            return "列表";
        } else {
            return "未知";
        }
    };

    useEffect(() => {
        loadKeyData();
    }, [props.client, props.curKey]);
    return (
        <div style={{padding:"10px 10px"}}>
            <Descriptions size="small" bordered column={2}>
                <Descriptions.Item label="数据类型" span={2}>{getDataTypeStr()}</Descriptions.Item>
                <Descriptions.Item label="空闲时间">{dataIdleTime ?? ""}</Descriptions.Item>
                <Descriptions.Item label="过期时间">{dataTtl ?? ""}</Descriptions.Item>
            </Descriptions>
            <div style={{height:"calc(100vh - 160px)",overflowY:"auto",paddingTop:"10px"}}>
                {dataType == "string" && (
                    <StringValue client={props.client} curKey={props.curKey}/>
                )}
                {dataType == "set" && (
                    <SetValue client={props.client} curKey={props.curKey}/>
                )}
                {dataType == "zset" && (
                    <SortedSetValue client={props.client} curKey={props.curKey}/>
                )}
                {dataType == "hash" && (
                    <HashValue client={props.client} curKey={props.curKey}/>
                )}
                {dataType == "list" && (
                    <ListValue client={props.client} curKey={props.curKey}/>
                )}
            </div>
        </div>
    );
}

export default Detail;